import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { Checkbox, Badge } from 'antd';
import DataEditTable from '../DataEditTable'
import * as datetime from '../../../utils/datetime'
import clone from '../../../utils/clone'
class Step3 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }
    handleCheckChange(e) {
        const daoName = this.props.daoName
        const checked = e.target.checked;
        this.props.dispatch({
            type: `${daoName}_DataImport/setIgnoreErr`,
            payload: { ignoreErr: checked }
        });
    }
    getTableHeaders() {
        let { columns, dataMaps } = this.props
        let headers = []
        columns.forEach((c, i) => {
            let h = {};
            h.title = c;
            h.sorter = false;
            h.width = 150;
            let dMap = null;
            for (let j = 0; j < dataMaps.length; j++) {
                dMap = dataMaps[j]
                if (dMap.SrcColIndex === i) {
                    h.dataIndex = dMap.DestColName
                    h.key = dMap.DestColName;
                    h.canEdit = true;
                    break
                }
            }
            if (!h.dataIndex) {
                h.dataIndex = "col_" + i;
                h.key = "col_" + i;
            }
            const cont = this.getControl(h.dataIndex)
            if (cont && cont.dataType === "date") {
                h.render = (data) => {
                    const obj = new Date(data);
                    if (isNaN(obj.getTime())) {
                        return data
                    }
                    return data ? datetime.format(obj, "yyyy-MM-dd") : ""
                };
            }
            h.dispaly = true;
            headers.push(h)
        })
        return headers;
    }
    getControl(name) {
        const controls = this.props.controls
        let cont = null;
        for (let i = 0; i < controls.length; i++) {
            if (controls[i].name === name) {
                cont = controls[i]
                break;
            }
        }
        return cont
    }
    getTableDatas(headers) {
        let errorDatas = this.props.errorDatas
        let tDatas = []
        errorDatas.forEach((d, k) => {
            let nData = {}
            nData.excelRowNum = d.RowIndex + 1
            if (this.state.hasColHeader) {
                nData.excelRowNum++
            }
            for (let i = 0; i < d.DataValues.length; i++) {
                nData[headers[i].dataIndex] = d.DataValues[i]
            }
            nData.$attachIfnos = []
            for (let i = 0; i < d.ErrorInfos.length; i++) {
                let errInfo = { ...d.ErrorInfos[i] }
                errInfo.Kind = "danger"
                nData.$attachIfnos.push(errInfo)
            }
            tDatas.push(nData)
        })
        return tDatas
    }
    isEditValid() {
        let errorDatas = this.refs.dataTable.getAllData()
        let isOk = true
        for (let i = 0; i < errorDatas.length; i++) {
            if (errorDatas[i].$attachIfnos && errorDatas[i].$attachIfnos.length > 0) {
                isOk = false;
                break
            }
        }
        return isOk;
    }
    getErrorDatas() {
        let errorDatas = []
        let datas = this.refs.dataTable.getAllData()
        let num = this.props.hasColHeader ? 2 : 1
        datas.forEach((d, i) => {
            let errorData = {};
            let strVals = []
            errorData.RowIndex = d.excelRowNum - num
            Object.keys(d).forEach((key) => {
                if (key !== "excelRowNum" && key.substr(0, 1) != "$") {
                    strVals.push(d[key]);
                }
            });
            errorData.DataValues = strVals;
            errorData.ErrorInfos = [];
            d.$attachIfnos.forEach((ai) => {
                let eInfo = {}
                eInfo.ColIndex = ai.ColIndex;
                eInfo.Message = ai.Message;
                errorData.ErrorInfos.push(eInfo)
            })
            errorDatas.push(errorData)
        })
        return errorDatas
    }
    convertControls(controls) {
        let newConts = clone(controls)
        newConts.map((c, i) => {
            if (c.type === "cascader-select" || c.type === "checkbox-group") {
                c.type = "tree-select"
            }
            if (c.data) {
                c.data.forEach(d => {
                    d.value = d.label
                })
            } else if (c.fetch) {
                c.optionTpl = "label"
                c.valueTpl = c.optionTpl
            }
            c.dataType = "string"
        })
        return newConts
    }
    render() {
        let { success, successCount, errorDatas, ignoreErr, controls, daoName, errorMsg, modelName } = this.props;
        let errorcount = errorDatas.length
        let errMag = "。"
        let msg2 = ""
        if (errorcount > 0 && errorcount <= 50) {
            errMag = "；错误的数据见下表，请在表中修改后再次执行导入！"    
        } else if (errorcount > 50) {
            errMag = "；错误的数据见下表，错误比较多，请在excel中修改后，重新导入！"
        }
        let msg = null
        if (success && (errorMsg == "" || errorMsg.length === 0)) {
            msg = <div>数据导入完成，成功<Badge count={successCount} overflowCount={1000000} style={{ backgroundColor: '#87d068' }} />行, {errorcount === 0 ? "没有" : ""}失败<Badge count={errorcount} overflowCount={1000} />行{errMag}</div>
        } else {
            const infos = errorMsg.split("|")
            msg = <div style={{ color: 'red' }}><p>数据校验失败</p>{infos.map(err => <p>{err}</p>)}</div>
        }

        if (errorcount > 0) {
            msg2 = <div><Checkbox checked={ignoreErr} onChange={this.handleCheckChange.bind(this)}>忽略这些错误数据，只导入正确的数据！</Checkbox></div>
        }
        let headers = this.getTableHeaders()
        let data = this.getTableDatas(headers)
        let width = (headers.length + 1) * 100
        let dataTable = ""
        const newConts = this.convertControls(controls)
        if (errorcount > 0) {
            dataTable = <DataEditTable width={width} height={338} columns={headers} controls={newConts} ref="dataTable"
                dataSource={data} keyName="excelRowNum" daoName={modelName} />
        }
        return (<div style={{ display: this.props.visible ? "block" : "none" }}>
            <div>{msg}{msg2}</div>
            {dataTable}
        </div>)
    }
}
Step3.propTypes = {
    daoName: PropTypes.string,
    controls: PropTypes.array,
    paramNames: PropTypes.array,
    visible: PropTypes.bool

};
Step3.defaultProps = {
    daoName: "",
    controls: [],
    paramNames: [],
    visible: false
};
export default function step3Create(daoName) {
    function mapStateToProps(state, props) {
        const modelName = props.modelName ? props.modelName : daoName
        const { dataMaps, columns, success, successCount, errorDatas, ignoreErr, errorMsg } = state[`${daoName}_DataImport`];
        return {
            dataMaps, columns, success, successCount, errorDatas, ignoreErr, errorMsg, modelName
        }
    }
    return connect(mapStateToProps, null, null, { withRef: true })(Step3);
}
